<?php
namespace app\vedio\controller;
use app\home\service\DoubanService;
use app\spider\service\QueryFilmService;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use QL\QueryList;
use QL\Ext\CurlMulti;
use think\Controller;
use think\Db;

class Tv extends BaseController
{

    public function test() {
        $client = new Client(['timeout'  => 2.0,]);
    }

    public function tags()
    {
        $type = $this->request->get('type', 'tv');
        $client = new Client(['timeout'  => 2.0,]);

        $response = $client->request('GET', 'https://movie.douban.com/j/search_tags?type=' . $type . '&source=');
        $res = (string) $response->getBody();
        $res = json_decode($res,true);
        if (empty($res)) {
            return $this->_returnJson([]);
        }
        $tags = array_map(function($val) {
            return ['name' => $val];
        }, $res['tags']);
        return $this->_returnJson($tags);
    }


    public function lists()
    {
        $start = $this->request->get('start', 0);
        $size = $this->request->get('size', 20);

        $playable =  $this->request->get('playable', 'on');
        $tag =  $this->request->get('tag');
        if (empty($tag)) {
            $tag = '热门';
        }
        $sort_type = $this->request->get('recommend');
        $type = $this->request->get('type', 'tv');

        $listApi = str_replace(['{type}','{tag}', '{sort}', '{page_start}', '{playable}', '{size}'], [$type, $tag, $sort_type, $start, $playable, $size], DoubanService::API_LIST);
        $doubanService = new DoubanService();
        $response = $doubanService->request($listApi);
        if ($response === false) {
            return $this->_returnJson([]);
        }
        $res = $doubanService->parseListResponse($response);
        return $this->_returnJson($res);
    }


    public function detail()
    {
        $id = $this->request->get('id');

        $doubanService = new DoubanService();
        $detailApi = str_replace('{id}', $id, DoubanService::API_DETAIL);
        $response = $doubanService->request($detailApi, null, 'get',['User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',]);
        $res = $doubanService->parseDetailResponse($response);


        $tv['title'] = $res['name'];
        $tv['cover'] = $res['image'];

        $tv['director'] = [];
        foreach ($res['director'] as $key => $v) {
            $name = explode(' ', $v['name']);
            $tv['director'][] = array_shift($name) . '(导演)';
            if ($key >= 1) {
                break;
            }
        }

        $tv['actor'] = [];
        foreach ($res['actor'] as $key => $v) {
            $name = explode(' ', $v['name']);
            $tv['actor'][] = array_shift($name);
            if ($key >= 2) {
                break;
            }
        }

        $tv['author'] = [];
        foreach ($res['author'] as $key => $v) {
            $name = explode(' ', $v['name']);
            $tv['author'][] = array_shift($name);
            if ($key >= 1) {
                break;
            }
        }

        $tv['content'] = $res['description'];
        $tv['genre'] = $res['genre'];

        $tv['rate'] = $res['aggregateRating']['ratingValue'];
        $tv['rating_count'] = $res['aggregateRating']['ratingCount'];
        if ($tv['rating_count'] >= 10000) {
            $tv['rating_count'] = round($tv['rating_count']/10000, 2) . '万';
        }
        if (is_array($res['play_urls'])) {
            $play_urls = [];
            foreach ($res['play_urls'] as $play_url) {
                $play_urls[] = [[ 'ep' => '播放', 'play_link' => $play_url['link']]];
            }
            $tv['play_urls'] = $play_urls;
        } else {
            $tv['play_urls'] = $res['play_urls'];
        }

        return $this->_returnJson($tv);
    }


    public function photos()
    {
        $id = $this->request->get('id');
        $photosApi = str_replace(array('{id}', '{type}'), array($id, 'S'), DoubanService::API_DETAIL_PHOTOS);

        $doubanService = new DoubanService();
        $photosResponse = $doubanService->request($photosApi);
        if ($photosResponse) {
            $photos = $doubanService->parseDetailPhotosResponse($photosResponse);
        } else {
            $photos = [];
        }

        return $this->_returnJson($photos);
    }


    public function playUrls()
    {
        $id = $this->request->get('key');
        $photosApi = str_replace(array('{key}'), array($id), DoubanService::API_PLAY_URL_JS);

        $doubanService = new DoubanService();
        $response = $doubanService->request($photosApi);
        if ($response) {
            $sources = $doubanService->parsePlayUrlJsResponse($response);
        } else {
            $sources = [];
        }


        foreach ($sources as $key => $source) {
            foreach ($source as $k => $s) {
                $link = str_replace('http://www.douban.com/link2/?url=', '', $s['play_link']);
                $link = urldecode($link);
                $name = $s['ep'] . '集';
                $source[$k] = [
                    'ep' => $name,
                    'play_link' => $link
                ];
            }
            $sources[$key] = $source;
        }

        return $this->_returnJson($sources);
    }

}
